from rest_framework.serializers import ModelSerializer, ListField, SlugRelatedField, ValidationError
from certificate_manager.models import Cate, DepartRestrict, Level
from .departrestrict import DepartRestrictSerializer
from .level import NestedLevelSerializer, LevelSerializer

class CateSerializer(ModelSerializer):
        restricts = DepartRestrictSerializer(many=True, required=False)
        # 这里需要一个QuerySet
        levels = NestedLevelSerializer(many=True, required=False)

        class Meta:
                model = Cate
                fields = ['pk', 'name', 'nested_cate', 'collect_part', 'layer', 'restricts', 'levels']
                read_only_fields = ['layer']


        def validate(self, attrs):
                if 'collect_part' in attrs and attrs['collect_part'] == Cate.LEVEL:
                        if 'levels' not in attrs:
                                raise ValidationError(f'If collect_part set to {Cate.LEVEL}, then levels field is needed')
                return attrs


        def create(self, validated_data):
                restricts = validated_data.pop('restricts', [])
                levels = validated_data.pop('levels', [])
                cate = Cate.objects.create(**validated_data)
                cate.save()

                for restrict in restricts:
                        DepartRestrict.objects.create(cate=cate, **restrict).save()

                if validated_data['collect_part'] == Cate.LEVEL:
                        # 创建相关level
                        for l in levels:
                                print('xx', l)
                                p_l = Level.objects.create(name=l['name'], cate=cate)
                                p_l.save()
                                for ll in l['nested_level']:
                                        c_l = Level.objects.create(name=ll['name'], nested_level=p_l)
                                        c_l.save()
                                
                return cate

        def to_representation(self, cate):
                res = super().to_representation(cate)
                if cate.collect_part == Cate.LEVEL:
                        # 这里就给出限制了，我们必须指定子类目
                        res['levels'] = LevelSerializer(cate.level_set.exclude(nested_level=None), many=True).data
                res['restricts'] = DepartRestrictSerializer(cate.departrestrict_set, many=True).data
                return res

        def update(self, instance, validated_data):
                # 我们先这样写吧
                instance.name = validated_data['name']
                if instance.nested_cate != validated_data['nested_cate']:
                        # 我们需要更新其大小
                        if validated_data['nested_cate']:
                                layer = validated_data['nested_cate'].layer + 1
                        else:
                                layer = None
                        instance.layer = layer

                instance.save()
                return instance

